package 算法.leetcode.offer.lkh;

import java.util.Arrays;

/**
 * @author lchenglong
 * @date 2022/4/20
 */
public class LKH34 {

    public static void main(String[] args) {
        int[] nums = new int[]{5,6,6,6,6,7,7,8,8,10};
        int target = 6;
        LKH34 instance = new LKH34();
        int[] ans = instance.searchRange(nums, target);
        System.out.println(Arrays.toString(ans));

    }
    public int[] searchRange(int[] nums, int target) {
        int len = nums.length;
        // 边界条件
        if (len == 0) return new int[]{-1,-1};
        if (len == 1) return target == nums[0]?new int[]{0,0}:new int[]{-1,-1};
        // 二分查找找到target
        int l = 0,r = len-1;
        int mid = -1;
        while (l<=r){
          mid = (l+r)/2;
          if (nums[mid] == target) {
              break;
          } else if (nums[mid]<target){
              l = mid +1;
          } else {
              r = mid - 1;
          }
        }
        if (nums[mid]!=target)return new int[]{-1,-1};
        int i=mid,j = mid;
        for (;i>=0&&j<len;){
            boolean f = false;
            if (i-1>=0 &&nums[i-1]  == target){
                i--;
                f = true;
            }
            if (j+1<len && nums[j+1] == target){
                j++;
                f = true;
            }
            if (!f)break;
        }
        return new int[]{i,j};
    }
}
